#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
管理员相关路由
"""
import csv
import io
import os
import shutil
from datetime import datetime
from fastapi import APIRouter, Request, Form, File, UploadFile, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from fastapi.templating import Jinja2Templates

from ..database import get_db_connection, row_to_dict, rows_to_dict_list
from ..utils.config import config
from ..utils.security import hash_password
from ..auth.session import verify_admin
from ..password.health import generate_password_health_report

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/admin", response_class=HTMLResponse)
async def admin_dashboard(request: Request):
    """管理员仪表板"""
    try:
        user = verify_admin(request)
    except HTTPException:
        return RedirectResponse(url="/login", status_code=302)
    
    conn = get_db_connection()
    
    # 基础统计信息
    user_count = conn.execute("SELECT COUNT(*) as count FROM users").fetchone()['count']
    password_count = conn.execute("SELECT COUNT(*) as count FROM passwords").fetchone()['count']
    share_count = conn.execute("SELECT COUNT(*) as count FROM password_shares").fetchone()['count']
    
    # 活跃用户数
    active_users = conn.execute("""
        SELECT COUNT(DISTINCT user_id) as count 
        FROM user_sessions 
        WHERE expires_at > datetime('now')
    """).fetchone()['count']
    
    # 今日新增统计
    today_users = conn.execute("""
        SELECT COUNT(*) as count 
        FROM users 
        WHERE DATE(created_at) = DATE('now')
    """).fetchone()['count']
    
    today_passwords = conn.execute("""
        SELECT COUNT(*) as count 
        FROM passwords 
        WHERE DATE(created_at) = DATE('now')
    """).fetchone()['count']
    
    today_shares = conn.execute("""
        SELECT COUNT(*) as count 
        FROM password_shares 
        WHERE DATE(created_at) = DATE('now')
    """).fetchone()['count']
    
    # 今日访问次数
    today_access = conn.execute("""
        SELECT COUNT(*) as count 
        FROM access_logs 
        WHERE DATE(accessed_at) = DATE('now')
    """).fetchone()['count']
    
    # 系统状态信息（简化版，不依赖psutil）
    import os
    import time
    
    # 获取系统运行时间（简化版）
    try:
        # 使用进程启动时间作为近似值
        import psutil
        uptime_seconds = psutil.boot_time()
        from datetime import datetime
        boot_time = datetime.fromtimestamp(uptime_seconds)
        uptime = datetime.now() - boot_time
        uptime_str = f"{uptime.days}天 {uptime.seconds//3600}小时"
        
        # 获取内存使用情况
        memory = psutil.virtual_memory()
        memory_percent = memory.percent
        memory_used = f"{memory.used / (1024**3):.1f}GB"
        memory_total = f"{memory.total / (1024**3):.1f}GB"
        
        # 获取磁盘使用情况
        disk = psutil.disk_usage('/')
        disk_percent = (disk.used / disk.total) * 100
        disk_used = f"{disk.used / (1024**3):.1f}GB"
        disk_total = f"{disk.total / (1024**3):.1f}GB"
    except ImportError:
        # 如果没有psutil，使用简化的系统信息
        uptime_str = "运行中"
        memory_percent = 50  # 默认值
        memory_used = "N/A"
        memory_total = "N/A"
        disk_percent = 30  # 默认值
        disk_used = "N/A"
        disk_total = "N/A"
    except Exception:
        uptime_str = "未知"
        memory_percent = 0
        memory_used = "未知"
        memory_total = "未知"
        disk_percent = 0
        disk_used = "未知"
        disk_total = "未知"
    
    # 获取数据库文件大小
    try:
        db_size = os.path.getsize('data/database.db')
        if db_size < 1024:
            db_size_str = f"{db_size} B"
        elif db_size < 1024 * 1024:
            db_size_str = f"{db_size / 1024:.1f} KB"
        else:
            db_size_str = f"{db_size / (1024 * 1024):.1f} MB"
    except:
        db_size_str = "未知"
    
    conn.close()
    
    return templates.TemplateResponse("admin/dashboard.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full'),
        "user_count": user_count,
        "password_count": password_count,
        "share_count": share_count,
        "active_users": active_users,
        "today_users": today_users,
        "today_passwords": today_passwords,
        "today_shares": today_shares,
        "today_access": today_access,
        "uptime": uptime_str,
        "memory_percent": memory_percent,
        "memory_used": memory_used,
        "memory_total": memory_total,
        "disk_percent": disk_percent,
        "disk_used": disk_used,
        "disk_total": disk_total,
        "db_size": db_size_str,
        "db_size_bytes": db_size if 'db_size' in locals() else 0,
        "user": user
    })


@router.get("/admin/users", response_class=HTMLResponse)
async def admin_users(request: Request):
    """用户管理页面"""
    try:
        user = verify_admin(request)
    except HTTPException:
        return RedirectResponse(url="/login", status_code=302)
    
    return templates.TemplateResponse("admin/users.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full'),
        "user": user
    })


@router.get("/admin/settings", response_class=HTMLResponse)
async def admin_settings(request: Request):
    """系统设置页面"""
    try:
        user = verify_admin(request)
    except HTTPException:
        return RedirectResponse(url="/login", status_code=302)
    
    return templates.TemplateResponse("admin/settings.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_full'),
        "user": user,
        "current_config": dict(config['DEFAULT'])
    })


@router.post("/api/settings")
async def update_settings(
    request: Request,
    app_name: str = Form(...),
    company_short: str = Form(...),
    company_full: str = Form(...),
):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """更新系统设置API"""
    try:
        # 更新配置
        config.set('DEFAULT', 'app_name', app_name)
        config.set('DEFAULT', 'company_short', company_short)
        config.set('DEFAULT', 'company_full', company_full)
       
        # 保存配置文件
        with open('config/config.ini', 'w', encoding='utf-8') as configfile:
            config.write(configfile)
        
        return {"message": "设置更新成功，重启应用后生效"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设置更新失败: {str(e)}")


@router.get("/api/system/stats")
async def get_system_stats(request: Request):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """获取系统统计信息API"""
    conn = get_db_connection()

    # 基础统计
    user_count = conn.execute("SELECT COUNT(*) as count FROM users").fetchone()['count']
    password_count = conn.execute("SELECT COUNT(*) as count FROM passwords").fetchone()['count']
    share_count = conn.execute("SELECT COUNT(*) as count FROM password_shares").fetchone()['count']
    access_count = conn.execute("SELECT COUNT(*) as count FROM access_logs").fetchone()['count']

    # 活跃用户数（有会话的用户）
    active_users = conn.execute("""
        SELECT COUNT(DISTINCT user_id) as count 
        FROM user_sessions 
        WHERE expires_at > datetime('now')
    """).fetchone()['count']

    # 今日新增密码
    today_passwords = conn.execute("""
        SELECT COUNT(*) as count 
        FROM passwords 
        WHERE DATE(created_at) = DATE('now')
    """).fetchone()['count']

    # 今日访问次数
    today_access = conn.execute("""
        SELECT COUNT(*) as count 
        FROM access_logs 
        WHERE DATE(accessed_at) = DATE('now')
    """).fetchone()['count']

    # 用户角色分布
    role_distribution = conn.execute("""
        SELECT role, COUNT(*) as count 
        FROM users 
        WHERE is_active = 1 
        GROUP BY role
    """).fetchall()

    # 最近7天的访问统计
    recent_accesses = conn.execute("""
        SELECT DATE(accessed_at) as date, COUNT(*) as count
        FROM access_logs
        WHERE accessed_at >= datetime('now', '-7 days')
        GROUP BY DATE(accessed_at)
        ORDER BY date
    """).fetchall()

    # 最活跃的分享
    top_shares = conn.execute("""
        SELECT ps.share_token, ps.access_count, p.url, u.username
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        JOIN users u ON p.user_id = u.id
        ORDER BY ps.access_count DESC
        LIMIT 5
    """).fetchall()

    # 系统信息
    try:
        import psutil
        # 系统运行时间
        uptime_seconds = psutil.boot_time()
        from datetime import datetime
        boot_time = datetime.fromtimestamp(uptime_seconds)
        uptime = datetime.now() - boot_time
        uptime_str = f"{uptime.days}天 {uptime.seconds//3600}小时"

        # 内存使用情况
        memory = psutil.virtual_memory()
        memory_percent = memory.percent
        memory_used = f"{memory.used / (1024**3):.1f}GB"
        memory_total = f"{memory.total / (1024**3):.1f}GB"

        # 磁盘使用情况
        disk = psutil.disk_usage('/')
        disk_percent = (disk.used / disk.total) * 100
        disk_used = f"{disk.used / (1024**3):.1f}GB"
        disk_total = f"{disk.total / (1024**3):.1f}GB"
    except ImportError:
        # 如果没有psutil，使用简化的系统信息
        uptime_str = "运行中"
        memory_percent = 50  # 默认值
        memory_used = "N/A"
        memory_total = "N/A"
        disk_percent = 30  # 默认值
        disk_used = "N/A"
        disk_total = "N/A"
    except Exception:
        uptime_str = "未知"
        memory_percent = 0
        memory_used = "未知"
        memory_total = "未知"
        disk_percent = 0
        disk_used = "未知"
        disk_total = "未知"

    # 获取数据库文件大小
    try:
        db_size = os.path.getsize('data/database.db')
        if db_size < 1024:
            db_size_str = f"{db_size} B"
        elif db_size < 1024 * 1024:
            db_size_str = f"{db_size / 1024:.1f} KB"
        else:
            db_size_str = f"{db_size / (1024 * 1024):.1f} MB"
    except:
        db_size_str = "未知"

    conn.close()

    # 处理角色分布数据
    role_data = {"admin": 0, "user": 0}
    for role in role_distribution:
        role_data[role['role']] = role['count']

    return {
        "basic_stats": {
            "user_count": user_count,
            "password_count": password_count,
            "share_count": share_count,
            "access_count": access_count,
            "active_users": active_users,
            "today_passwords": today_passwords,
            "today_access": today_access,
            "uptime": uptime_str,
            "memory_percent": memory_percent,
            "memory_used": memory_used,
            "memory_total": memory_total,
            "disk_percent": disk_percent,
            "disk_used": disk_used,
            "disk_total": disk_total,
            "db_size": db_size_str,
            "db_size_bytes": db_size if 'db_size' in locals() else 0
        },
        "role_distribution": role_data,
        "recent_accesses": rows_to_dict_list(recent_accesses),
        "top_shares": rows_to_dict_list(top_shares)
    }


@router.post("/api/system/backup")
async def create_backup(request: Request):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """创建数据备份API"""
    try:
        # 创建备份目录
        backup_dir = "data/backups"
        os.makedirs(backup_dir, exist_ok=True)
        
        # 生成备份文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = f"{backup_dir}/database_backup_{timestamp}.db"
        
        # 复制数据库文件
        shutil.copy2("data/database.db", backup_file)
        
        return {"message": f"备份创建成功: {backup_file}"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"备份创建失败: {str(e)}")


@router.get("/api/system/backups")
async def list_backups(request: Request):
    try:
        user = verify_admin(request)
    except HTTPException:
        raise HTTPException(status_code=401, detail="请先登录")
    """获取备份列表API"""
    import glob
    
    try:
        backup_dir = "data/backups"
        if not os.path.exists(backup_dir):
            return {"backups": []}
        
        backup_files = glob.glob(f"{backup_dir}/database_backup_*.db")
        backups = []
        
        for file_path in backup_files:
            file_name = os.path.basename(file_path)
            file_size = os.path.getsize(file_path)
            file_time = os.path.getmtime(file_path)
            
            # 格式化文件大小
            if file_size < 1024:
                size_str = f"{file_size} B"
            elif file_size < 1024 * 1024:
                size_str = f"{file_size / 1024:.1f} KB"
            else:
                size_str = f"{file_size / (1024 * 1024):.1f} MB"
            
            backups.append({
                "filename": file_name,
                "path": file_path,
                "size": size_str,
                "created_at": datetime.fromtimestamp(file_time).strftime("%Y-%m-%d %H:%M:%S")
            })
        
        # 按创建时间倒序排列
        backups.sort(key=lambda x: x['created_at'], reverse=True)
        
        return {"backups": backups}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取备份列表失败: {str(e)}")